package com.itheima.reggie.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.service.CategoryService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;

@RestController
@RequestMapping("/category")
public class CategoryController {

    @Autowired
    private CategoryService categoryService;
    /**
     * 新增分类
     * @param session
     * @param category
     * @return
     */
    @PostMapping
    public R save(HttpSession session, @RequestBody Category category){

//        Long  empId = (Long) session.getAttribute("employee");
//        category.setCreateTime(LocalDateTime.now());
//        category.setUpdateTime(LocalDateTime.now());
//        category.setCreateUser(empId);
//        category.setUpdateUser(empId);

        boolean save = categoryService.save(category);
        return save?R.success("新增分类成功！"):R.error("新增分类失败！");
    }

    /**
     * 分类分页查询
     *
     */
    @GetMapping("/page")
    public R page(int page,int pageSize){
        Page<Category> pageInfo = new Page(page,pageSize);
        LambdaQueryWrapper<Category> qw = new LambdaQueryWrapper<>();
        qw.orderByDesc(Category::getSort).orderByDesc(Category::getUpdateTime);
        pageInfo= categoryService.page(pageInfo, qw);
        HashMap map = new HashMap();
        List<Category> records = pageInfo.getRecords();
        long total = pageInfo.getTotal();
        map.put("records",records);
        map.put("total",total);
        return R.success(map);
    }

    /**
     * 删除分类
     */
    @DeleteMapping
    public R delete(Long id){
        //有些复杂了，因为要判断删除的分类是否有菜品 或者是套餐
        R r = categoryService.deleteById(id);
        return r;

    }

    /**
     * 修改分类
     */


    @PutMapping
    public R update(@RequestBody Category category){

        boolean b = categoryService.updateById(category);
        return b?R.success("修改成功"):R.error("修改失败");
    }

    /**
     * 新增菜品
     * 先查询回显分类数据
     *
     */
    @GetMapping("/list")
    public R list(Integer type){
        LambdaQueryWrapper<Category> qw = new LambdaQueryWrapper<>();
        qw.eq(type!=null,Category::getType,type);
        qw.orderByAsc(Category::getSort);
        List<Category> list = categoryService.list(qw);
        return list!=null?R.success(list):R.error("查询失败！");
    }
//    @GetMapping("/list")
//    public R list(){
//        LambdaQueryWrapper<Category> qw = new LambdaQueryWrapper<>();
//
//        qw.orderByAsc(Category::getSort);
//        List<Category> list = categoryService.list(qw);
//        return list!=null?R.success(list):R.error("查询失败！");
//    }


}
